/*********************************************************
          File Name:move.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Wed 23 Mar 2016 08:31:36 PM CST
**********************************************************/

#include <iostream>
#include <cstring>

struct Node
{
  struct Node* next;
  int idx;
};

void mv(Node** old_, Node** new_)
{
  Node* ptr = *old_;
  while(ptr != nullptr)
  {
    Node* next = ptr->next;
    ptr->next = (*new_ == nullptr ? nullptr : (*new_)->next);
    if(*new_ == nullptr)
      *new_ = ptr;
    else
      (*new_)->next = ptr;
    ptr = next;
  }
  delete [] old_;
  old_ = nullptr;
}

void show(Node** new_)
{
  Node* node = *new_;
  Node* next = nullptr;
  while(node != nullptr)
  {
    next = node->next;
    std::cout << node->idx << std::endl;
    node = next;
  }
  std::cout << "--------\n";
}

void clear(Node** l)
{
  Node* ptr = *l;
  Node* next = nullptr;
  while(ptr != nullptr)
  {
    next = ptr->next;
    delete ptr;
    ptr = next;
  }
  delete [] l;
}

int main()
{
  Node** old = new Node*[1];
  memset(old, 0, sizeof(old[0]));

  Node* node = nullptr;
  for(int i = 0; i < 5; ++i)
  {
    node = *old;
    Node* n = new Node;
    n->idx = i;
    n->next = (node == nullptr ? nullptr : node->next);
    if(node == nullptr)
      *old = n;
    else
      (*old)->next = n;
  }

  Node** new_ = new Node*[1];
  memset(new_, 0, sizeof(new_[0]));

  std::cout << "before `mv` (old)\n";
  show(old);
  mv(old, new_);
  std::cout << "mv old => new_ (new_)\n";
  show(new_);
  old = new Node*[1];
  memset(old, 0, sizeof(old[0]));
  mv(new_, old);
  std::cout << "mv new_ => old (old)\n";
  show(old);

  clear(old);
}
